package co.fitstart.market.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.demo2do.core.persistence.GenericDaoSupport;
import com.demo2do.core.persistence.annotation.Dynamic;
import com.demo2do.core.utils.CollectionUtils;

import co.fitstart.entity.market.InvitationStatus;
import co.fitstart.entity.market.MarketBatchCourseware;
import co.fitstart.entity.market.MarketCourse;
import co.fitstart.entity.market.MarketCourseRound;
import co.fitstart.entity.market.MarketDailyCourseware;
import co.fitstart.entity.market.MarketInvitationRecord;
import co.fitstart.entity.market.MarketMonthlyCourseware;
import co.fitstart.entity.market.Questionnaire;
import co.fitstart.entity.market.QuestionnaireStat;
import co.fitstart.entity.market.template.MarketBatchCoursewareTemplate;
import co.fitstart.entity.market.template.MarketDailyCoursewareTemplate;
import co.fitstart.entity.market.template.MarketMonthlyCoursewareTemplate;
import co.fitstart.entity.user.User;
import co.fitstart.market.dao.CoursewareDao;
import co.fitstart.market.dao.MarketInvitationRecordDao;
import co.fitstart.market.dao.QuestionnaireDao;
import co.fitstart.market.dao.UserDao;
import co.fitstart.market.handler.SmsSender;
import co.fitstart.market.service.QuestionnaireService;

/**
 * 
 * @author dan
 *
 */
@Service("questionnaireService")
public class QuestionnaireServiceImpl implements QuestionnaireService{
    
    @Dynamic
    private QuestionnaireDao questionnaireDao;
    
    @Dynamic
    private MarketInvitationRecordDao invitationRecordDao;
    
    @Dynamic
    private CoursewareDao coursewareDao;
    
    @Dynamic
    private MarketInvitationRecordDao marketInvitationRecordDao;
    
    @Dynamic
    private UserDao userDao;
    
    @Autowired
    private SmsSender smsSender;
    
    @Autowired
    private GenericDaoSupport genericDaoSupport;
    
    @Value("#{ctx['system.host']}")
    private String path;

    /*
     * (non-Javadoc)
     * @see co.fitstart.market.service.QuestionnaireService#load(java.lang.String)
     */
    public Questionnaire load(String userOpenid) {
        return questionnaireDao.load(userOpenid);
    }

    /*
     * (non-Javadoc)
     * @see co.fitstart.market.service.QuestionnaireService#create(co.fitstart.entity.market.QuestionnaireStat, co.fitstart.entity.user.User)
     */
    public void check(QuestionnaireStat stat, String openid) {
        // create questionnaire first
        Questionnaire questionnaire = new Questionnaire(stat, openid);
        genericDaoSupport.save(questionnaire);
        
        // if this user is invitee then change record status
        MarketInvitationRecord invitationRecord = invitationRecordDao.load(openid, InvitationStatus.INVITED);
        if(invitationRecord != null) {
            genericDaoSupport.update(invitationRecord.changeStatus(InvitationStatus.SIGN_UP));
            
            // 发送短信
            List<MarketInvitationRecord> records = marketInvitationRecordDao.list(invitationRecord.getInviter(), InvitationStatus.SIGN_UP);
            int invitees = records.size();
            User inviter = userDao.loadUser(invitationRecord.getInviter());
            String url = path + "/questionnaires/result";
            if(invitees == 1) {
                smsSender.sendFullInviteUserNotice(inviter.getMobile(), invitees, url);
            }
        }
        
        // 如果用户存在，创建marketCourseRound
        User user = userDao.loadUser(openid);
        if(user != null) {
            this.createCourse(questionnaire, user);
        }
        
    }
    
    /*
     * (non-Javadoc)
     * @see co.fitstart.market.service.QuestionnaireService#createCourse(co.fitstart.entity.market.Questionnaire, co.fitstart.entity.user.User)
     */
    public void createCourse(Questionnaire questionnaire, User user) {
        // choose marketCourse by questionnaire's scoreTotal
      List<MarketCourse> result = coursewareDao.listMarketCourse();
      Map<String, MarketCourse> courses = CollectionUtils.constructMapValueFromList(result, "courseLevel.alias");
      int scoreTotal = questionnaire.getScoreTotal() * 2;
      if(scoreTotal <= 70) {
          this.participate(user, courses.get("middle"));
      } else {
          this.participate(user, courses.get("senior"));
      }
    }
    
    /**
     * 
     * @param user
     * @param course
     */
    private void participate(User user, MarketCourse course) {
        
        // Step1. create marketCourseRound
        MarketCourseRound courseRound = new MarketCourseRound(course, user);
        genericDaoSupport.save(courseRound);
        
        // Step2. create marketMonthlyCourseware, marketBatchCourseware, marketDailyCourseware and marketCourseware
        List<MarketMonthlyCoursewareTemplate> monthlyTemplates = coursewareDao.listMonthlyCoursewareTemplate(course);
        for(MarketMonthlyCoursewareTemplate monthlyTemplate : monthlyTemplates) {
            MarketMonthlyCourseware monthly = new MarketMonthlyCourseware(monthlyTemplate, courseRound);
            genericDaoSupport.save(monthly);
            
            List<MarketBatchCoursewareTemplate> batchTemplates = monthlyTemplate.getBatchCoursewares();
            for(MarketBatchCoursewareTemplate batchTemplate : batchTemplates) {
                MarketBatchCourseware batch = new MarketBatchCourseware(batchTemplate, monthly);
                genericDaoSupport.save(batch);
                
                List<MarketDailyCoursewareTemplate> dailyTemplates = batchTemplate.getDailycoursewares();
                for(MarketDailyCoursewareTemplate dailyTemplate : dailyTemplates) {
                    MarketDailyCourseware daily = new MarketDailyCourseware(dailyTemplate, batch);
                    genericDaoSupport.save(daily);
                }
            }
        }
    }

}
